package org.fqh.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.fqh.common.ResponseCode;
import org.fqh.entity.TBlog;
import org.fqh.entity.TUser;
import org.fqh.service.TBlogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* @author fqh 
* @version 创建时间：2018年3月20日 下午2:08:26
* 类说明
*/
@RequestMapping("/blogs")
@Controller
public class BlogController {
		
	   private static Logger log = LoggerFactory.getLogger(BlogController.class);
	   
	   @Autowired
	   TBlogService blogService; 

	   @RequestMapping("/{id}")
	   public String getBlogById(Model model,@PathVariable(value="id")int id) {
		   TBlog blog = blogService.getById(id); 
		   if(blog!=null) {
			   model.addAttribute("blog", blog);
			   return "/blog/detail"; 
		   }else {
			   return "404";
		   }
		 
	   }
	   @GetMapping("/addBlog")
	   public String toAdd() {
		   return "/blog/addBlog";   
	   }
	   
	
	   @PostMapping("/add")
	   public @ResponseBody ResponseCode add(Model model,TBlog blog,HttpSession session) {
		  TUser user = (TUser)session.getAttribute("user");
		  ResponseCode code =new ResponseCode();
		  if(user!=null) {
			  blog.setCreateTime(new Date());
			  blog.setCreateUserId(user.getId());
			  int id = blogService.createTBlog(blog);
			  code.setCode(200);
			  code.setMsg("发布成功!");
			  code.setUrl("/blogs/"+id);
		  }else {
			  code.setCode(500);
			  code.setMsg("用户未登录!");
			  code.setUrl("");
			  
		  }
		  return code;
		
	   }
}
